package com.xmb.wechat.lsn;

import android.text.TextUtils;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.xmb.wechat.application.WechatStartApplication;
import com.xmb.wechat.bean.GroupTalkBean;
import com.xmb.wechat.bean.WechatContactBean;
import com.xmb.wechat.bean.WechatLastMsgBean;
import com.xmb.wechat.bean.WechatLastMsgBean_;
import com.xmb.wechat.bean.WechatMsgBean;

import java.util.Date;

import javax.annotation.Nullable;

import io.objectbox.Box;

/**
 * 消息发送中心
 */
public class SendMsgCenter {

    /**
     * 转账(群聊没有)
     */
    public static void sendZhuanZhang(SendMsgListener lsn, long msgSenderID, long talkerID, long moneySenderID, double money, String remark) {
        WechatMsgBean msg = new WechatMsgBean();
        msg.setMsgType(WechatMsgBean.MSG_TYPE_ZHUAN_ZHANG);
        msg.setMoney(money);
        msg.setMoneyRemark(remark);
        msg.setMsgSenderID(msgSenderID);
        msg.setTalkerID(talkerID); //聊天对象
        msg.setMsgTime(new Date());
        msg.setMoneySenderID(moneySenderID);//转账者的ID
        WechatStartApplication.getBoxStore().boxFor(WechatMsgBean.class).put(msg);
        LogUtils.d((msg.isMySend() ? "【我】" : "【" + msgSenderID + "】") + "转账：" + msg);
        lsn.onSendSuc();

        //更新首页聊天列表：
        updateLastMsgList(msg, msg.getMoneySenderID() == -1 ? "[转账]待朋友收款" : "[转账]请你确认收款");
    }


    /**
     * 确认收款(群聊没有)
     */
    public static void confirmReceiveZhuanZhang(SendMsgListener lsn, WechatMsgBean wechatMsgBean) {
        //1.先将记录标记为已收款：
        wechatMsgBean.setReceiveMoney(true);
        wechatMsgBean.setReceiveTime(new Date());//收款时间
        wechatMsgBean.setMoneyRemark("已被领取");//收款时间
        WechatStartApplication.getBoxStore().boxFor(WechatMsgBean.class).put(wechatMsgBean);
        LogUtils.d("确认收款之原记录：" + wechatMsgBean);

        //2.再插入一条新记录，该记录是领取的信息，会在聊天记录里显示的：
        WechatMsgBean receiveMsgBean = new WechatMsgBean();
        receiveMsgBean.setPid(wechatMsgBean.getId());//领取转账的记录的PID指向转账的记录!!!!!!!
        receiveMsgBean.setMsgSenderID(wechatMsgBean.getMsgSenderID() == -1 ?
                wechatMsgBean.getTalkerID() : -1); //不一样的是这里：领取者与转账者应该相反!!!!!!!
        receiveMsgBean.setReceiveMoney(true);//也标记为已收款
        receiveMsgBean.setMoneyRemark("已收钱");
        receiveMsgBean.setReceiveTime(wechatMsgBean.getReceiveTime());//收款时间
        receiveMsgBean.setMsgType(WechatMsgBean.MSG_TYPE_ZHUAN_ZHANG);
        receiveMsgBean.setMoney(wechatMsgBean.getMoney());
        receiveMsgBean.setTalkerID(wechatMsgBean.getTalkerID()); //聊天对象
        receiveMsgBean.setMsgTime(wechatMsgBean.getMsgTime());
        receiveMsgBean.setMoneySenderID(wechatMsgBean.getMoneySenderID());//转账者的ID
        WechatStartApplication.getBoxStore().boxFor(WechatMsgBean.class).put(receiveMsgBean);
        LogUtils.d("确认收款之收款记录：" + receiveMsgBean);
        lsn.onSendSuc();

        //更新首页聊天列表：
        updateLastMsgList(wechatMsgBean, wechatMsgBean.getMoneySenderID() == -1 ? "[转账]朋友已确认收款" : "[转账]你已确认收款");
    }

    /**
     * 发送红包
     */
    public static void sendRedpkg(SendMsgListener lsn, long msgSenderID, boolean isRoomChat, long talkerID, String moneyStr, String remark) {
        try {
            Double.parseDouble(moneyStr);
        } catch (Exception e) {
            ToastUtils.showShort("金额输入有误");
            e.printStackTrace();
            return;
        }
        if (TextUtils.isEmpty(remark))
            remark = "恭喜发财，大吉大利";
        WechatMsgBean msg = new WechatMsgBean();
        msg.setMsgType(WechatMsgBean.MSG_TYPE_RED_PKG);
        msg.setMoney(Double.parseDouble(moneyStr));
        msg.setMoneyRemark(remark);
        msg.setMoneySenderID(msgSenderID);//转账者的ID
        msg.setRoomChat(isRoomChat);
        msg.setMsgSenderID(msgSenderID);
        msg.setTalkerID(talkerID); //聊天对象
        msg.setMsgTime(new Date());
        WechatStartApplication.getBoxStore().boxFor(WechatMsgBean.class).put(msg);
        lsn.onSendSuc();

        //更新首页聊天列表：
        updateLastMsgList(msg, "[微信红包]" + remark);
    }

    /**
     * 领取红包【个人红包】
     */
    public static void confirmReceiveSingleRedpkg(SendMsgListener lsn, WechatMsgBean wechatMsgBean, WechatContactBean contactBean) {
        //1.先将记录标记为已收款：
        wechatMsgBean.setReceiveMoney(true);
        wechatMsgBean.setReceiveTime(new Date());//收款时间
        WechatStartApplication.getBoxStore().boxFor(WechatMsgBean.class).put(wechatMsgBean);
        LogUtils.d("【个人红包】之原记录：" + wechatMsgBean);

        //2.再插入一条新记录，该记录是领取的信息，会在聊天记录里显示的：
        String receiveStr = "【对象】领取了【对象2】的";
        if (wechatMsgBean.getMsgSenderID() == -1) {//我发的红包，对方领取：
            receiveStr = receiveStr.replace("【对象】", contactBean.getName());
            receiveStr = receiveStr.replace("【对象2】", "你");
        } else {//对方发的红包，我领取：
            receiveStr = receiveStr.replace("【对象】", "你");
            receiveStr = receiveStr.replace("【对象2】", contactBean.getName());
        }
        WechatMsgBean receiveMsgBean = new WechatMsgBean();
        receiveMsgBean.setPid(wechatMsgBean.getId());//领取红包的记录的PID指向转账的记录!!!!!!!
        receiveMsgBean.setMsgSenderID(wechatMsgBean.getMsgSenderID() == -1 ? wechatMsgBean.getTalkerID() : -1); //不一样的是这里：领取者与转账者应该相反!!!!!!!
        receiveMsgBean.setReceiveMoney(true);//也标记为已收款
        receiveMsgBean.setMoneyRemark(receiveStr);//【对象】领取了【对象2】的红包
        receiveMsgBean.setReceiveTime(wechatMsgBean.getReceiveTime());//收款时间
        receiveMsgBean.setMsgType(WechatMsgBean.MSG_TYPE_RED_PKG_RECEIVE);
        receiveMsgBean.setMoney(wechatMsgBean.getMoney());
        receiveMsgBean.setTalkerID(wechatMsgBean.getTalkerID()); //聊天对象
        receiveMsgBean.setMsgTime(wechatMsgBean.getMsgTime());
        receiveMsgBean.setMoneySenderID(wechatMsgBean.getMoneySenderID());//转账者的ID
        WechatStartApplication.getBoxStore().boxFor(WechatMsgBean.class).put(receiveMsgBean);
        LogUtils.d("【个人红包】之收款记录：" + receiveMsgBean);
        lsn.onSendSuc();

        //更新首页聊天列表：
        updateLastMsgList(receiveMsgBean, receiveStr + "红包");
    }

    /**
     * 领取红包【群聊红包】
     */
    public static void sendRedpkgReceive(SendMsgListener lsn, long talkerID, WechatContactBean sender, WechatContactBean receiver, boolean isReceiveFinish) {
        String receiveStr = "【对象】领取了【对象2】的";
        if (sender.getId() == -1) {//我发的红包
            receiveStr = receiveStr.replace("【对象2】", "你");
        } else {//对方发的红包
            receiveStr = receiveStr.replace("【对象2】", sender.getName());
        }
        if (receiver.getId() == -1) {//我收的红包
            receiveStr = receiveStr.replace("【对象】", "你");
        } else {//对方收的红包
            receiveStr = receiveStr.replace("【对象】", receiver.getName());
        }
        //创建消息记录
        WechatMsgBean receiveMsgBean = new WechatMsgBean();
        receiveMsgBean.setMsgSenderID(sender.getId());
        receiveMsgBean.setReceiveMoney(true);//也标记为已收款
        receiveMsgBean.setMoneyRemark(receiveStr);//【对象】领取了【对象2】的红包
        receiveMsgBean.setReceiveTime(new Date());//收款时间
        receiveMsgBean.setReceiveFinish(isReceiveFinish);

        receiveMsgBean.setMsgType(WechatMsgBean.MSG_TYPE_RED_PKG_RECEIVE);
        receiveMsgBean.setRoomChat(true);
        receiveMsgBean.setTalkerID(talkerID); //聊天对象
        receiveMsgBean.setMoneySenderID(sender.getId());//发红包者的ID
        receiveMsgBean.setMsgTime(new Date());
        WechatStartApplication.getBoxStore().boxFor(WechatMsgBean.class).put(receiveMsgBean);
        lsn.onSendSuc();

        //更新首页聊天列表：
        updateLastMsgList(receiveMsgBean, receiveStr + "红包");
    }

    /**
     * 发送文字消息
     */
    public static void sendString(SendMsgListener lsn, long msgSenderID, boolean isRoomChat, long talkerID, String content) {
        WechatMsgBean msg = new WechatMsgBean();
        msg.setMsgType(WechatMsgBean.MSG_TYPE_STRING);
        msg.setContent(content);
        msg.setMsgSenderID(msgSenderID);
        msg.setRoomChat(isRoomChat);
        msg.setTalkerID(talkerID);
        msg.setMsgTime(new Date());
        WechatStartApplication.getBoxStore().boxFor(WechatMsgBean.class).put(msg);
        LogUtils.d((msg.isMySend() ? "【我】" : "【对方】") + "发送聊天：" + msg);
        lsn.onSendSuc();

        //更新首页聊天列表：
        updateLastMsgList(msg, content);
    }

    /**
     * 发送语音
     */
    public static void sendVoice(SendMsgListener lsn, long msgSenderID, boolean isRoomChat, long talkerID, int length, boolean isRead) {
        WechatMsgBean msg = new WechatMsgBean();
        msg.setMsgType(WechatMsgBean.MSG_TYPE_VOICE);
        msg.setContent(length + "");
        msg.setMsgSenderID(msgSenderID);
        msg.setRoomChat(isRoomChat);
        msg.setTalkerID(talkerID); //聊天对象
        msg.setMsgTime(new Date());
        msg.setRead(isRead);
        WechatStartApplication.getBoxStore().boxFor(WechatMsgBean.class).put(msg);
        lsn.onSendSuc();

        //更新首页聊天列表：
        updateLastMsgList(msg, "[语音]");
    }

    /**
     * 发送视频|语音通话
     */
    public static void sendCall(SendMsgListener lsn, long msgSenderID, boolean isRoomChat, long talkerID, boolean isVideoCall, String content) {
        WechatMsgBean msg = new WechatMsgBean();
        msg.setMsgType(isVideoCall ? WechatMsgBean.MSG_TYPE_VIDEO_CALL :
                WechatMsgBean.MSG_TYPE_VOICE_CALL);
        msg.setContent(content);
        msg.setMsgSenderID(msgSenderID);
        msg.setRoomChat(isRoomChat);
        msg.setTalkerID(talkerID); //聊天对象
        msg.setMsgTime(new Date());
        WechatStartApplication.getBoxStore().boxFor(WechatMsgBean.class).put(msg);
        lsn.onSendSuc();

        //更新首页聊天列表：
        updateLastMsgList(msg, isVideoCall ? "[视频通话]" : "[语音通话]");
    }

    /**
     * 发送图片
     */
    public static void sendImg(SendMsgListener lsn, long msgSenderID, boolean isRoomChat, long talkerID, String pickImgPath) {
        if (pickImgPath == null) {
            lsn.onSendError("请先选择要发送的图片");
            return;
        }
        WechatMsgBean msg = new WechatMsgBean();
        msg.setMsgType(WechatMsgBean.MSG_TYPE_IMG);
        msg.setContent(pickImgPath);
        msg.setMsgSenderID(msgSenderID);
        msg.setRoomChat(isRoomChat);
        msg.setTalkerID(talkerID); //聊天对象
        msg.setMsgTime(new Date());
        WechatStartApplication.getBoxStore().boxFor(WechatMsgBean.class).put(msg);
        lsn.onSendSuc();

        //更新首页聊天列表：
        updateLastMsgList(msg, "[图片]");
    }

    /**
     * 发送系统提示
     */
    public static void sendSystip(SendMsgListener lsn, boolean isRoomChat, long talkerID, String content) {
        WechatMsgBean msg = new WechatMsgBean();
        msg.setMsgType(WechatMsgBean.MSG_TYPE_SYS_TIP);
        msg.setContent(content);
        msg.setTalkerID(talkerID); //聊天对象
        msg.setRoomChat(isRoomChat);
        msg.setMsgTime(new Date());
        WechatStartApplication.getBoxStore().boxFor(WechatMsgBean.class).put(msg);
        LogUtils.d("发送系统提示：" + content);
        lsn.onSendSuc();

        //更新首页聊天列表：
        updateLastMsgList(msg, content);
    }

    /**
     * 发送时间
     */
    public static void sendTime(SendMsgListener lsn, boolean isRoomChat, long talkerID, Date date) {
        WechatMsgBean msg = new WechatMsgBean();
        msg.setMsgType(WechatMsgBean.MSG_TYPE_TIME);
        msg.setMsgTime(date);
        msg.setTalkerID(talkerID); //聊天对象
        msg.setRoomChat(isRoomChat);
        WechatStartApplication.getBoxStore().boxFor(WechatMsgBean.class).put(msg);
        LogUtils.d("发送Time：" + msg);
        lsn.onSendSuc();

        //该消息类型不更新首页聊天列表
    }

    /**
     * 发送名片
     */
    public static void sendBuinessCards(SendMsgListener lsn, long msgSenderID, boolean isRoomChat, long talkerID, WechatContactBean wechatContactBean) {
        WechatMsgBean msg = new WechatMsgBean();
        msg.setMsgType(WechatMsgBean.MSG_TYPE_BUINESS_CARDS);
        msg.setMsgSenderID(msgSenderID);
        msg.setMsgTime(new Date());
        msg.setBusinessCardsId(wechatContactBean.getId());
        msg.setTalkerID(talkerID); //聊天对象
        msg.setRoomChat(isRoomChat);
        WechatStartApplication.getBoxStore().boxFor(WechatMsgBean.class).put(msg);
        lsn.onSendSuc();

        //更新首页聊天列表：
        updateLastMsgList(msg, "[名片]");
    }

    /**
     * 更新首页的聊天列表，显示最新的消息
     *
     * @param wechatMsgBean
     */
    public static void updateLastMsgList(WechatMsgBean wechatMsgBean, String msgContent) {
        long talkerID;
        WechatLastMsgBean lastMsg;
        Box<WechatLastMsgBean> box = WechatStartApplication.getBoxStore().boxFor(WechatLastMsgBean.class);
        if (wechatMsgBean.isRoomChat()) {//群聊
            //先查联系人
            GroupTalkBean groupTalkBean = WechatStartApplication.getBoxStore().boxFor(GroupTalkBean.class).get(wechatMsgBean.getTalkerID());
            talkerID = groupTalkBean.getId();

        } else {//单聊
            //先查联系人
            WechatContactBean contactBean = WechatStartApplication.getBoxStore().boxFor(WechatContactBean.class).get(wechatMsgBean.getTalkerID());
            talkerID = contactBean.getId();
        }
        //创建最新消息对象(先查再new)
        lastMsg = box.query().equal(WechatLastMsgBean_.talkerID, talkerID).build().findFirst();
        if (lastMsg == null)
            lastMsg = new WechatLastMsgBean();
        Date lastDate;
        if (wechatMsgBean.getReceiveTime() != null) {
            lastDate = (wechatMsgBean.getMsgTime().getTime() > wechatMsgBean.getReceiveTime().getTime() ? wechatMsgBean.getMsgTime() : wechatMsgBean.getReceiveTime());
        } else {
            lastDate = wechatMsgBean.getMsgTime();
        }
        //最新消息的时间：
        lastMsg.setTime(lastDate);
        lastMsg.setTalkerID(talkerID);
        lastMsg.setMsgContent(msgContent);
        lastMsg.setRoomChat(wechatMsgBean.isRoomChat());//是否是群聊
        lastMsg.setSenderID(wechatMsgBean.getMsgSenderID());//发送人ID（只适用于群聊中）
        box.put(lastMsg);
    }

    /**
     * 更新首页的聊天列表，显示最新的消息（目前只有单聊）
     *
     * @param wechatMsgBean
     * @param contactBean   可传NULL
     */
    public static void updateLastMsgList1(WechatMsgBean wechatMsgBean, @Nullable WechatContactBean contactBean, String msgContent) {
        //        //如果contactBean为NULL，则去DB里查询出来：
        //        if (contactBean == null)
        //            contactBean = WechatStartApplication.getBoxStore().boxFor(WechatContactBean.class).get(wechatMsgBean.getTalkerID());
        //
        //        //先去DB里查询，如果没有再New新的：
        //        Box<WechatLastMsgBean> box = WechatStartApplication.getBoxStore().boxFor(WechatLastMsgBean.class);
        //        WechatLastMsgBean lastMsg = box.query().equal(WechatLastMsgBean_.talkerID, contactBean.getId()).build().findFirst();
        //        if (lastMsg == null)
        //            lastMsg = new WechatLastMsgBean();
        //        lastMsg.setRoomChat(wechatMsgBean.isRoomChat());//是否是群聊
        //        Date lastDate;
        //        if (wechatMsgBean.getReceiveTime() != null) {
        //            lastDate = (wechatMsgBean.getMsgTime().getTime() > wechatMsgBean.getReceiveTime().getTime() ? wechatMsgBean.getMsgTime() : wechatMsgBean.getReceiveTime());
        //        } else {
        //            lastDate = wechatMsgBean.getMsgTime();
        //        }
        //        //最新消息的时间：
        //        lastMsg.setTime(lastDate);
        //        lastMsg.setAvatarSrc(contactBean.getAvatarSrc());
        //        lastMsg.setAvatar(contactBean.getAvatar());
        //        lastMsg.setTalkerID(contactBean.getId());
        //        lastMsg.setTalkerName(contactBean.getName());
        //        lastMsg.setMsgContent(msgContent);
        //        box.put(lastMsg);
    }


    public interface SendMsgListener {
        void onSendSuc();

        /**
         * @param errorMsg 发送MSG失败的提示
         */
        void onSendError(String errorMsg);
    }

}
